package com.ruoyi.project.purchase.service.impl;

import java.util.Date;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.inventory.domain.RyInventory;
import com.ruoyi.project.inventory.mapper.RyInventoryMapper;
import com.ruoyi.project.purchase.domain.RyDepotDetail;
import com.ruoyi.project.purchase.domain.RyDepotHead;
import com.ruoyi.project.purchase.domain.RyOrderBill;
import com.ruoyi.project.purchase.domain.pojo.DepotDetailBean;
import com.ruoyi.project.purchase.domain.pojo.DepotHeadItem;
import com.ruoyi.project.purchase.mapper.RyDepotDetailMapper;
import com.ruoyi.project.purchase.mapper.RyOrderBillMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.warehouse.domain.RyDepot;
import com.ruoyi.project.warehouse.domain.RyDepotItem;
import com.ruoyi.project.warehouse.mapper.RyDepotItemMapper;
import com.ruoyi.project.warehouse.mapper.RyDepotMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.purchase.mapper.RyPurchaseOrderMapper;
import com.ruoyi.project.purchase.domain.RyPurchaseOrder;
import com.ruoyi.project.purchase.service.IRyPurchaseOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购订单Service业务层处理
 *
 * @author you
 * @date 2022-10-11
 */
@Service
public class RyPurchaseOrderServiceImpl implements IRyPurchaseOrderService
{
    @Autowired
    private RyPurchaseOrderMapper ryPurchaseOrderMapper;


    @Autowired
    private RyDepotDetailMapper ryDepotDetailMapper;

    @Autowired
    private RyDepotMapper ryDepotMapper;

    @Autowired
    private RyDepotItemMapper ryDepotItemMapper;

    @Autowired
    private RyOrderBillMapper ryOrderBillMapper;

    @Autowired
    private RyInventoryMapper ryInventoryMapper;



    /**
     * 查询采购订单
     *
     * @param id 采购订单主键
     * @return 采购订单
     */
    @Override
    public RyPurchaseOrder selectRyPurchaseOrderById(Long id)
    {
        return ryPurchaseOrderMapper.selectRyPurchaseOrderById(id);
    }

    /**
     * 查询采购订单列表
     *
     * @param ryPurchaseOrder 采购订单
     * @return 采购订单
     */
    @Override
    public List<RyPurchaseOrder> selectRyPurchaseOrderList(RyPurchaseOrder ryPurchaseOrder)
    {
        return ryPurchaseOrderMapper.selectRyPurchaseOrderList(ryPurchaseOrder);
    }

    /**
     * 新增采购订单
     *
     * @param ryPurchaseOrder 采购订单
     * @return 结果
     */
    @Override
    public int insertRyPurchaseOrder(RyPurchaseOrder ryPurchaseOrder)
    {
        ryPurchaseOrder.setCreateTime(DateUtils.getNowDate());
        return ryPurchaseOrderMapper.insertRyPurchaseOrder(ryPurchaseOrder);
    }

    /**
     * 根据条件筛选可关联的采购订单
     * @param list
     * @return
     */
    public List<RyPurchaseOrder> allUsed(List<Long> list){
        return ryPurchaseOrderMapper.allUsed(list);
    }

    /**
     * 新增采购订单表及单据子表信息
     * 实质上只新增了采购订单主表，子表数据只需要修改相应信息即可
     */
    @Override
    @Transactional
    public AjaxResult addDepotHeadAndDetail(DepotHeadItem depotHeadItem){
        System.out.println("linkHeadId---->" + depotHeadItem.getLinkHeadId());
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //判断是否有子表数据
        List<RyDepotItem> tableData = depotHeadItem.getTableData();
        if(tableData == null || tableData.size() ==0){
            return AjaxResult.error("子表数据不存在");
        }

        //新增采购订单信息
        RyPurchaseOrder ryPurchaseOrder = new RyPurchaseOrder();
        ryPurchaseOrder.setNumber(depotHeadItem.getNumber());//单据号
        ryPurchaseOrder.setContractNumber(depotHeadItem.getContractNumber());//采购合同号
        ryPurchaseOrder.setOrganId(depotHeadItem.getOrganId());//供应商id
        ryPurchaseOrder.setFileName(depotHeadItem.getFileName());
        ryPurchaseOrder.setSalesMan(depotHeadItem.getSalesMan());
        ryPurchaseOrder.setCreateTime(DateUtils.getNowDate());//创建时间
        ryPurchaseOrder.setCreator(user.getUserId());//操作员
        ryPurchaseOrder.setRemark(depotHeadItem.getRemark());
        ryPurchaseOrder.setStatus("0");//默认未审核
        ryPurchaseOrder.setShippingStatus("0");//默认未发货
        ryPurchaseOrder.setType("其他");
        ryPurchaseOrder.setSubType("采购订单");

        //判断是否关联了项目总清单
        if(depotHeadItem.getLinkHeadId() != null) {//关联项目
            ryPurchaseOrder.setLinkHeadId(depotHeadItem.getLinkHeadId());//关联项目id
            ryPurchaseOrder.setProjectHeadId(depotHeadItem.getLinkHeadId());

            //修改关联项目总清单的明细，生成订单的明细项将is_create_order修改为Y
            //根据项目总清单id和物品id修改状态
            RyDepotItem param = new RyDepotItem();
            param.setHeaderId(depotHeadItem.getLinkHeadId());
            param.setIsCreateOrder("Y");
            for(RyDepotItem ryDepotItem : tableData){
                //如果操作数量operNumber为0或者为null，则跳过此次循环，不进行入库操作
                if(ryDepotItem.getOperNumber() == null || ryDepotItem.getOperNumber() == 0){
                    continue;
                }
                param.setInventoryId(ryDepotItem.getInventoryId());
                ryDepotItemMapper.updateIsCreateOrder(param);
            }

        }

        int res = ryPurchaseOrderMapper.insertRyPurchaseOrder(ryPurchaseOrder);
        /**
         * 统计参数，用于统计明细入库数量
         * 如果totalInNum > 0 存在入库明细，则不需处理
         * 如果totalInNum <= 0 说明明细数据因为条件问题一条都没有入库，
         * 这时就主动抛出错误，使得事务生效，防止主表信息插入而明细表没有数据
         *
         */
        int totalInNum = 0;

        if(res > 0){
            //遍历明细数据，更新单据明细数据
            for(RyDepotItem ryDepotItem : tableData){
                //如果操作数量operNumber为0或者为null，则跳过此次循环，不进行入库操作
                if(ryDepotItem.getOperNumber() == null || ryDepotItem.getOperNumber() == 0){
                    continue;
                }
                //如果物品名或物品规格为空则跳过不处理
                if(StringUtils.isBlank(ryDepotItem.getInventorySpecifications()) || StringUtils.isBlank(ryDepotItem.getInventoryName())){
                    continue;
                }
                //判断物品是否存在物品库中
                RyInventory ryInventory = ryInventoryMapper.selectInfoByNameSpeci(ryDepotItem.getInventorySpecifications().replaceAll(" ","").toUpperCase(), ryDepotItem.getInventoryName().replaceAll(" ","").toUpperCase());
                if(ryInventory == null){
                    RyInventory ryInventory2 = new RyInventory();
                    // 物品名称
                    ryInventory2.setName(ryDepotItem.getInventoryName().replaceAll(" ",""));
                    // 规格
                    ryInventory2.setSpecifications(ryDepotItem.getInventorySpecifications().replaceAll(" ",""));
                    // wbs编码
                    ryInventory2.setWbs(ryDepotItem.getWbs());
                    // 品牌
                    if (ryDepotItem.getBrand() == null) {
                        ryInventory2.setBrand("/");
                    } else {
                        ryInventory2.setBrand(ryDepotItem.getBrand());
                    }
                    // 供应商ID
                    // ryInventory2.setSupplyId(ryDepotItem.getSupplyId().toString());
                    // 供应商
                    ryInventory2.setSupply(ryDepotItem.getSupply());
                    // 装填
                    ryInventory2.setStatus("0");
                    // 操作员
                    ryInventory2.setOperator(ryDepotItem.getInOperateMan());
                    // 单位
                    ryInventory2.setUnit("");
                    // 单价
                    ryInventory2.setUnitPrice(ryDepotItem.getUnitPrice());
                    // 库位
                    ryInventory2.setLocation(ryDepotItem.getLocation());
                    ryInventoryMapper.insertRyInventory(ryInventory2);
                    ryDepotItem.setInventoryId(ryInventory2.getId());
                }

                ryDepotItem.setHeaderId(ryPurchaseOrder.getId());//设置刚生成的采购订单id
                ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
                totalInNum += 1;
            }
        }
        //如果统计结果小于等于0,则主动抛出异常
        if(totalInNum <= 0){
            throw new RuntimeException("实际采购数据出现数据为空或其他问题");
//            return AjaxResult.error("入库数据出现入库数量为空或其他问题");
        }
        return AjaxResult.success("新增成功");
    }


    /**
     * 修改采购订单
     */
    @Override
    @Transactional
    public AjaxResult editDepotHeadAndDetail(DepotHeadItem depotHeadItem){
        System.out.println("depotDetailBean---->" + depotHeadItem);
        //获取用户信息
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //判断是否有子表数据
        List<RyDepotItem> tableData = depotHeadItem.getTableData();
        if(tableData == null || tableData.size() ==0){
            return AjaxResult.error("子表数据不存在");
        }

        //修改主表数据
        RyPurchaseOrder ryPurchaseOrder = new RyPurchaseOrder();
        ryPurchaseOrder.setId(depotHeadItem.getId());//主键，用于定位修改数据
        ryPurchaseOrder.setDeliverTime(depotHeadItem.getDeliverTime());
        ryPurchaseOrder.setContractNumber(depotHeadItem.getContractNumber());
        ryPurchaseOrder.setOperTime(DateUtils.getNowDate());
        ryPurchaseOrder.setFileName(depotHeadItem.getFileName());
        ryPurchaseOrder.setRemark(depotHeadItem.getRemark());
        //修改
        ryPurchaseOrderMapper.updateRyPurchaseOrder(ryPurchaseOrder);

        //将子表数据先删除，根据主表id删除
        ryDepotItemMapper.deleteDepotItemByHeadId(ryPurchaseOrder.getId());
        //遍历明细数据，新增单据明细数据
        for(RyDepotItem ryDepotItem : tableData){
            ryDepotItem.setHeaderId(ryPurchaseOrder.getId());//设置刚生成的采购订单id
            ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
        }


        //将票据子表数据先删除，根据订单id删除
        ryOrderBillMapper.deleteRyOrderBillByOrderId(ryPurchaseOrder.getId());

        //判断是否有发票信息
        List<RyOrderBill> billTableData = depotHeadItem.getBillTableData();
        //关联发票信息
        if(billTableData != null && billTableData.size() != 0){

            //遍历明细数据，新增单据明细数据
            for(RyOrderBill ryOrderBill : billTableData){
                ryOrderBill.setOrderId(ryPurchaseOrder.getId());//设置刚生成的采购订单id
                ryOrderBillMapper.insertRyOrderBill(ryOrderBill);
            }
        }

        return AjaxResult.success("修改成功");
    }


    /**
     * 查询单据主表及子表信息
     *
     * @param id 单据主表主键
     * @return 单据主表及子表信息
     */
    @Override
    public DepotHeadItem selectRyDepotDetailById(Long id)
    {

        DepotHeadItem depotHeadItem = new DepotHeadItem();
        RyPurchaseOrder ryPurchaseOrder = ryPurchaseOrderMapper.selectRyPurchaseOrderById(id);
        //主表数据
        depotHeadItem.setId(ryPurchaseOrder.getId());
        depotHeadItem.setProjectCode(ryPurchaseOrder.getProjectCode());//项目代码
        depotHeadItem.setProjectName(ryPurchaseOrder.getProjectName());//项目名

        depotHeadItem.setNumber(ryPurchaseOrder.getNumber());//单据号
        depotHeadItem.setContractNumber(ryPurchaseOrder.getContractNumber());//采购合同号

        depotHeadItem.setCreator(ryPurchaseOrder.getCreator());//操作员
        depotHeadItem.setOperName(ryPurchaseOrder.getOperName());//操作员名称

        depotHeadItem.setCreateTime(ryPurchaseOrder.getCreateTime());
        depotHeadItem.setOperTime(ryPurchaseOrder.getOperTime());
        depotHeadItem.setFileName(ryPurchaseOrder.getFileName());
        depotHeadItem.setSalesMan(ryPurchaseOrder.getSalesMan());

        depotHeadItem.setOrganId(ryPurchaseOrder.getOrganId());//供应商id
        depotHeadItem.setCompanyName(ryPurchaseOrder.getCompanyName());//供应商/客户名
        depotHeadItem.setLinkHeadId(ryPurchaseOrder.getLinkHeadId());//关联项目id

        depotHeadItem.setDeliverTime(ryPurchaseOrder.getDeliverTime());
        depotHeadItem.setRemark(ryPurchaseOrder.getRemark());

        //子表数据
        List<RyDepotItem> tableData = ryDepotItemMapper.selectRyDepotItemByDepotId(id);
        //遍历子表待采购数量，如果是新增的物品数据，待采购数量可能为空，为了让前台不报错，则赋值为0.0
        for(RyDepotItem ryDepotItem : tableData){
            if(ryDepotItem.getAdvancePurchaseNum() == null){
                ryDepotItem.setAdvancePurchaseNum(0.0);
            }
        }
        depotHeadItem.setTableData(tableData);

        //子表数据
        List<RyOrderBill> billTableData = ryOrderBillMapper.selectRyOrderBillByOrderId(id);
        depotHeadItem.setBillTableData(billTableData);
        return depotHeadItem;
    }

    /**
     * 修改采购订单
     *
     * @param ryPurchaseOrder 采购订单
     * @return 结果
     */
    @Override
    public int updateRyPurchaseOrder(RyPurchaseOrder ryPurchaseOrder)
    {
        return ryPurchaseOrderMapper.updateRyPurchaseOrder(ryPurchaseOrder);
    }

    /**
     * 批量删除采购订单
     *
     * @param ids 需要删除的采购订单主键
     * @return 结果
     */
    @Override
    public int deleteRyPurchaseOrderByIds(Long[] ids)
    {
        return ryPurchaseOrderMapper.deleteRyPurchaseOrderByIds(ids);
    }

    /**
     * 删除采购订单信息
     *
     * @param id 采购订单主键
     * @return 结果
     */
    @Override
    public int deleteRyPurchaseOrderById(Long id)
    {
        return ryPurchaseOrderMapper.deleteRyPurchaseOrderById(id);
    }
}
